<!--  -->
<template>
  <div class="">
    <el-card class="box-card">
      <el-button
        v-if="checkUrls('/room/insertResource.do')"
        type="primary"
        @click="handleAddUser"
      >添加用户</el-button>
      <el-table :data="List" style="width: 100%;margin-top:30px;" border="" stripe>
        <el-table-column align="center" label="账号名" width="220">
          <template slot-scope="scope">
            <template v-if="scope.row.temp_edit">
              <el-input v-model="scope.row.accountName" class="edit-input" size="small"/>
            </template>
            <span v-else>{{ scope.row.accountName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户姓名" width="220">
          <template slot-scope="scope">
            <template v-if="scope.row.temp_edit">
              <el-input v-model="scope.row.name" class="edit-input" size="small"/>
            </template>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editPermission(scope.row)"
            >编辑数据权限</el-button>
            <template v-if="scope.row.temp_edit">
              <el-button
                size="mini"
                type="success"
                icon="el-icon-circle-check-outline"
                @click="saveRowEvent(scope.row)"
              >保存</el-button>
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-refresh"
                @click="cancelRowEvent(scope.$index,scope.row)"
              >取消</el-button>
            </template>
            <template v-else>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="editRowEvent(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="removeRowEvent(scope.row)"
              >删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog width="35%" :visible.sync="dialogVisible" title="修改用户信息">
      <el-form :model="userData" label-width="80px" label-position="left">
        <el-form-item label="账号名">
          <el-input v-model="userData.accountName" placeholder="角色名"/>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="userData.name" placeholder="角色名"/>
        </el-form-item>
        <el-form-item label="角色">
          <el-transfer
            v-model="role.roleValue"
            :data="role.roleData"
            :titles="['所有角色', '用户角色']"
            :button-texts="['删除', '添加']"
            filterable
            @change="handleChange"
            :render-content="renderContent"
          ></el-transfer>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog width="35%" :visible.sync="dialogVisible2" title="编辑数据权限">
      <el-form :model="formData" label-width="80px" lable-position="left">
        <el-form-item label="下拉列名">
          <el-select
            v-model="selectValue"
            @change="selecChange"
            value-key="lineUuid"
            placeholder="请选择"
          >
            <el-option
              v-for="item in permissionData"
              :key="item.lineUuid"
              :label="item.lineName"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下拉框">
          <el-radio-group v-model="radioData.selected">
            <el-radio v-for="(item,key,index) in radioData.data" :key="index" :label="key">{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible2=false">取消</el-button>
        <el-button type="primary" @click="confirm2">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { regist, getAll, updateUser } from "@/api/login";
import checkUrls from "@/utils/permission";
import {
  getRolesByUserGuid,
  updateUserRoles,
  getRolesLikeRoleName,
  getSelectByUser,
  addUserConditions,
  updateUserConditions
} from "@/api/manage";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      List: [],
      formData: {},
      permissionData: [],
      permissionKeys: [],
      dialogVisible: false,
      dialogVisible2: false,
      userData: {},
      role: {
        roleData: [],
        roleValue: []
      },
      addValue: [],
      delValue: [],
      condition: [
        {
          lineUUid: "",
          lineValue: ""
        }
      ],
      // radio: "",
      radioData: {},
      selectValue: ""
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    checkUrls,
    selecChange(value) {
      console.log("change", value);
      this.radioData = value;
    },
    fetchData() {
      getAll().then(res => {
        this.List = res.body;
      });
    },
    getAllRole() {
      this.role.roleData = [];
      getRolesLikeRoleName().then(res => {
        //所有接口
        for (let index = 0; index < res.body.length; index++) {
          this.role.roleData.push({
            key: res.body[index].guid,
            label: res.body[index].name,
            description: res.body[index].description
          });
        }
      });
      getRolesByUserGuid(this.userData.guid).then(res => {
        //模型所属接口
        this.role.roleValue = [];
        let urlKey = res.body.roles;
        for (let index = 0; index < urlKey.length; index++) {
          this.role.roleValue.push(urlKey[index].guid);
        }
      });
    },
    editPermission(row) {
      this.dialogVisible2 = true;
      this.userData.guid = row.guid;
      const data = { userGuid: row.guid };
      getSelectByUser(data).then(res => {
        if (res.body != null) {
          this.permissionData = res.body;
          for (let index = 0; index < res.body.length; index++) {
            if (res.body[index].selected != null) {
              this.radioData = res.body[index];
              this.radioData.selected = String(this.radioData.selected);
              console.log("radioselected", this.radioData);
              this.selectValue = this.radioData.lineName;
              console.log("radiovalue", this.radioData.selected);
            }
          }
        }
      });
    },
    handleAddUser() {
      this.List.unshift({ temp_edit: true });
    },
    saveRowEvent(row) {
      regist(row).then(response => {
        if ((response.code = 100)) {
          this.fetchData();
        }
      });
    },
    cancelRowEvent(index, row) {
      this.List.splice(index, 1);
    },
    editRowEvent(row) {
      this.dialogVisible = true;
      this.userData = row;
      this.getAllRole();
    },
    removeRowEvent(row) {},
    confirm() {
      const data = {
        addRoleGuids: this.addValue,
        delRoleGuids: this.delValue,
        userGuid: this.userData.guid
      };
      updateUserRoles(data).then(response => {
        if (response.code === 100) {
          this.getAllRole();
        }
      });
      updateUser(this.userData).then(response => {
        if (response.code === 100) {
          this.$message({ message: "修改成功!", type: "success" });
          this.dialogVisible = false;
        }
      });
    },
    confirm2() {
      let data = {
        lineUuid: this.radioData.lineUuid,
        userGuid: this.userData.guid,
        lineValue: this.radioData.selected
      };
      console.log("radioData", this.radioData);

      if (this.selectValue != "") {
        updateUserConditions(data).then(res => {});
      } else {
        addUserConditions(data).then(res => {});
      }
    },
    handleChange(value, direction, movedKeys) {
      let keyData = this.role.roleData.map(role => role.key);
      if (direction === "left") {
        for (let index = 0; index < movedKeys.length; index++) {
          if (keyData.includes(movedKeys[index])) {
            this.delValue.push(movedKeys[index]);
          }
          this.addValue = this.addValue.filter(
            item => item != movedKeys[index]
          );
        }
      } else {
        for (let index = 0; index < movedKeys.length; index++) {
          if (keyData.includes(movedKeys[index])) {
            this.addValue.push(movedKeys[index]);
          }
          this.delValue = this.delValue.filter(
            item => item != movedKeys[index]
          );
        }
      }
    },
    renderContent(h, option) {
      return (
        <el-popover
          placement="right"
          title={option.label}
          width="200"
          trigger="hover"
          content={option.description}
        >
          <span slot="reference">{option.label}</span>
        </el-popover>
      );
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchData();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.box-card {
  margin: 20px 10px 10px 10px;
}
</style>